import React, { useEffect, useState } from 'react';
import { Card, Col, message, Row, Tag, Anchor } from 'antd';
const { Link } = Anchor;
import { menuRoleMenuTreeSelectUsingGET } from '@/services/ctb-service/menu';
import { formatTreeSelectData } from '@/utils/utils';
import { useModel } from '@@/plugin-model/useModel';

const Home: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [menuTree, setMenuTree] = useState<any[]>([]);
  const dontShowMenuName = ['控制台', '个人', '若依官网'];
  const [currentAnchor, setCurrentAnchor] = useState<string>('#系统管理');

  const getCurrentAnchor = () => currentAnchor;

  const onChangeAnchor = (anchor: string) => {
    setCurrentAnchor(anchor);
  }

  const getMenu = async () => {
    // @ts-ignore
    menuRoleMenuTreeSelectUsingGET({ roleId: currentUser?.roles[0].roleId } as any).then(
      (res: any) => {
        if (res.code === 200) {
          let treeData = formatTreeSelectData(res.menus);
          // 先过滤dontShowMenuName中的菜单
          treeData = treeData.filter((item: any) => !dontShowMenuName.includes(item.title));
          setMenuTree(treeData);
          console.log(treeData);
        } else {
          message.warn(res.msg);
        }
      },
    );
  };

  useEffect(() => {
    getMenu();
  }, []);

  const boxPadding = 16;

  // 返回一个左右两个框的布局
  return (
    <div style={{ marginTop: '50px' }}>
      <Row align="middle" justify="center">
        <Col span={18}>
          {menuTree.map((item, index) => {
            return (
              <>
                <Tag color="default" style={{ fontSize: '18px', padding: '12px', margin: '96px 0 12px 0' }} id={item.title}>
                  {item.title}
                </Tag>
                <Row gutter={[boxPadding, boxPadding]} key={item.id}>
                  {item.children.map((subItem: any, index: React.Key | null | undefined) => {
                    return (
                      <Col span={3} key={subItem.id}>
                        <Card>{subItem.title}</Card>
                      </Col>
                    );
                  })}
                </Row>
              </>
            );
          })}
        </Col>
        <Col span={4}>
          <Anchor getCurrentAnchor={getCurrentAnchor} onChange={onChangeAnchor} style={{padding: '48px 0 0 48px'}}>
            {menuTree.map((item, index) => {
              return (
                <div style={{ padding: '12px 0' }}>
                  <Link href={`#${item.title}`} title={item.title} key={item.id} />
                </div>
              );
            })}
          </Anchor>
        </Col>
      </Row>
    </div>
  );
};

export default Home;
